#include "preHeader.h"
#include "GameMap.h"
#include "SceneMgr.h"

GameMap::GameMap(const MapInfo* pMapInfo)
: m_pMapInfo(pMapInfo)
, m_pScene(NULL)
, m_tileDefine(0,0,0,0)
, m_isInited(false)
{
}

GameMap::~GameMap()
{
	SAFE_DELETE(m_pScene);
}

void GameMap::Init()
{
	LoadDBRes();
	LoadSceneRes();
	m_isInited = true;
}

void GameMap::LoadDBRes()
{
	LoadMapZones();
	LoadMapGraveyards();
	LoadTeleportPoints();

	LoadCreatureSpawns();
	LoadStaticObjectSpawns();
}

void GameMap::LoadMapZones()
{
	auto pTable = sDBMgr.GetTable<MapZone>();
	for (auto itr = pTable->Begin(); itr != pTable->End(); ++itr) {
		const MapZone* pMapZone = &itr->second;
		if (pMapZone->map_id == m_pMapInfo->Id) {
			m_mapZones[pMapZone->map_type].push_back(pMapZone);
		}
	}
}

void GameMap::LoadMapGraveyards()
{
	auto pTable = sDBMgr.GetTable<MapGraveyard>();
	for (auto itr = pTable->Begin(); itr != pTable->End(); ++itr) {
		const MapGraveyard* pMapGraveyard = &itr->second;
		if (pMapGraveyard->map_id == m_pMapInfo->Id) {
			m_mapGraveyards[pMapGraveyard->map_type].push_back(pMapGraveyard);
		}
	}
}

void GameMap::LoadTeleportPoints()
{
	auto pTable = sDBMgr.GetTable<TeleportPoint>();
	for (auto itr = pTable->Begin(); itr != pTable->End(); ++itr) {
		const TeleportPoint* pTeleportPoint = &itr->second;
		if (pTeleportPoint->map_id == m_pMapInfo->Id) {
			m_teleportPoints[pTeleportPoint->map_type].push_back(pTeleportPoint);
		}
	}
}

void GameMap::LoadCreatureSpawns()
{
	auto pTable = sDBMgr.GetTable<CreatureSpawn>();
	for (auto itr = pTable->Begin(); itr != pTable->End(); ++itr) {
		const CreatureSpawn* pCreatureSpawn = &itr->second;
		if (pCreatureSpawn->map_id == m_pMapInfo->Id && !pCreatureSpawn->flags.isPlaceholder) {
			m_creatureSpawns[pCreatureSpawn->map_type].push_back(pCreatureSpawn);
		}
	}
}

void GameMap::LoadStaticObjectSpawns()
{
	auto pTable = sDBMgr.GetTable<StaticObjectSpawn>();
	for (auto itr = pTable->Begin(); itr != pTable->End(); ++itr) {
		const StaticObjectSpawn* pStaticObjectSpawn = &itr->second;
		if (pStaticObjectSpawn->map_id == m_pMapInfo->Id && !pStaticObjectSpawn->flags.isPlaceholder) {
			m_staticObjectSpawns[pStaticObjectSpawn->map_type].push_back(pStaticObjectSpawn);
		}
	}
}

void GameMap::LoadSceneRes()
{
	m_pScene = sSceneMgr.CreateAndGetScene(m_pMapInfo->strSceneFile);
	auto& sceneBound = m_pScene->GetSceneBound();
	REINIT_OBJECT(const_cast<TileDefine*>(&m_tileDefine),
		sceneBound.min.x, sceneBound.max.x, sceneBound.min.y, sceneBound.max.y);
}
